<?php
/**
 *
 * 版权所有：忠赢网站管理系统<www.51shunshi.com>

 * 日    期：2015-09-17
 * 版    本：1.0.0
 * 功能说明：模块公共文件。
 *
 **/


function UpImage($callBack = "image", $width = 100, $height = 100, $image = "")
{

    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" width=' . $width . ' height="' . $height . '"  src="' . U('Upload/uploadpic',
            array('Width' => $width, 'Height' => $height, 'BackCall' => $callBack)) . '"></iframe>
         <input type="hidden" ' . 'value = "' . $image . '"' . 'name="' . $callBack . '" id="' . $callBack . '">';
}

function BatchImage($callBack = "image", $width = 100, $height = 100, $image = "")
{
    
    echo '<iframe scrolling="no" frameborder="0" border="0" width=100% onload="this.height=this.contentWindow.document.body.scrollHeight;" src="' . U('Upload/batchpic',
            array('Width' => $width, 'Height' => $height, 'BackCall' => $callBack)) . '"></iframe>
		<input type="hidden" ' . 'value = "' . $image . '"' . 'name="' . $callBack . '" id="' . $callBack . '">';
}


/*
 * 函数：网站配置获取函数
 * @param  string $k      可选，配置名称
 * @return array          用户数据
*/
function setting($k = 'all')
{
    $cache = S($k);
    //如果缓存不为空直接返回
    if (null != $cache) {
        return $cache;
    }
    $data = '';
    $setting = M('setting');
    //判断是否查询全部设置项
    if ($k == 'all') {
        $setting = $setting->field('k,v')->select();
        foreach ($setting as $v) {
            $config[$v['k']] = $v['v'];
        }
        $data = $config;

    } else {
        $result = $setting->where("k='{$k}'")->find();
        $data = $result['v'];

    }
    //建立缓存
    if ($data) {
        S($k, $data);
    }
    return $data;
}

/**
 * 函数：格式化字节大小
 * @param  number $size 字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) {
        $size /= 1024;
    }
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 函数：加密
 * @param string            密码
 * @return string           加密后的密码
 */
function password($password)
{
    /*
    *后续整强有力的加密函数
    */
    return md5('Q' . $password . 'W');

}

/**
 * 随机字符
 * @param number $length 长度
 * @param string $type 类型
 * @param number $convert 转换大小写
 * @return string
 */
function random($length = 6, $type = 'string', $convert = 0)
{
    $config = array(
        'number' => '1234567890',
        'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );

    if (!isset($config[$type])) {
        $type = 'string';
    }
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) - 1;
    for ($i = 0; $i < $length; $i++) {
        $code .= $string{mt_rand(0, $strlen)};
    }
    if (!empty($convert)) {
        $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
    }
    return $code;
}

//获取所有的子级id
function category_get_sons($sid, &$array = array())
{
    //获取当前sid下的所有子栏目的id
    $categorys = M("category")->where("pid = {$sid}")->select();

    $array = array_merge($array, array($sid));
    foreach ($categorys as $category) {
        category_get_sons($category['id'], $array);
    }
    $data = $array;
    unset($array);
    return $data;

}


/**
 * 获取文章url地址
 * url结构：ttp://wwww.qwadmin.com/分类/子分类/子分类/id.html
 * 使用方法：模板中{:articleUrl(array('aid'=>$val['aid']))}
 *
 *
 * @param $data
 * @return $string
 */
function articleUrl($data)
{
    //如果数组为空直接返回空字符
    if (!$data) {
        return '';
    }
    //如果参数错误直接返回空字符
    if (!isset($data['aid'])) {
        return '';
    }

    $aid = (int)$data['aid'];

    //获取文章信息
    $article = M('article')->where(array('aid' => $aid))->find();
    //获取当前内容所在分类
    $category = M('category')->where(array('id' => $article['sid']))->find();
    //获取当前分类
    $categoryUrl = $category['dir'];
    //遍历获取当前文章所在分类的有上级分类并且组合url
    while ($category['pid'] <> 0) {
        $category = M('category')->where(array('id' => $category['pid']))->find();
        $categoryUrl = $category['dir'] . "/" . $categoryUrl;
        //如果上级分类已经无上级分类则退出
    }

    $categoryUrl = __ROOT__ . "/" . $categoryUrl;
    //组合文章url
    $articleUrl = $categoryUrl . '/' . $aid . ".html";
    return $articleUrl;

}

function pp($bool=false)
{
    list($callee) = debug_backtrace();
    $arguments = func_get_args();
    $totalArguments = count($arguments);

    echo "<fieldset class='dump'>" . PHP_EOL .
        "<legend>{$callee['file']} @ line: {$callee['line']}</legend>" . PHP_EOL .
        '<pre>';

    $i = 0;
    foreach ($arguments as $argument) {
        echo '<br /><strong>Debug #' . (++$i) . " of {$totalArguments}</strong>: ";

        if (! empty($argument)
            && (is_array($argument) || is_object($argument))
        ) {
            print_r($argument);
        } else {
            var_dump($argument);
        }
    }

    echo '</pre>' . PHP_EOL .
        '</fieldset>' . PHP_EOL;
    if(!$bool){

    }
}
function isMobile() {
    $mobile = array();
    static $mobilebrowser_list ='Mobile|iPhone|Android|WAP|NetFront|JAVA|OperasMini|UCWEB|WindowssCE|Symbian|Series|webOS|SonyEricsson|Sony|BlackBerry|Cellphone|dopod|Nokia|samsung|PalmSource|Xphone|Xda|Smartphone|PIEPlus|MEIZU|MIDP|CLDC';
    //note 获取手机浏览器
    if(preg_match("/$mobilebrowser_list/i", $_SERVER['HTTP_USER_AGENT'], $mobile)) {
        return true;
    }else{
        if(preg_match('/(mozilla|chrome|safari|opera|m3gate|winwap|openwave)/i', $_SERVER['HTTP_USER_AGENT'])) {
            return false;
        }else{
            if($_GET['mobile'] === 'yes') {
                return true;
            }else{
                return false;
            }
        }
    }
}


function mdate($time = NULL)
{
    date_default_timezone_set('PRC');
    $text = '';
    $time = $time === NULL || $time > time() ? time() : intval($time);
    $t = time() - $time; //时间差 （秒）
    if ($t == 0)
        $text = '刚刚';
    elseif ($t < 60)
        $text = $t . '秒前'; // 一分钟内
    elseif ($t < 60 * 60)
        $text = floor($t / 60) . '分钟前'; //一小时内
    elseif ($t < 60 * 60 * 24)
        $text = floor($t / (60 * 60)) . '小时前'; // 一天内
    elseif ($t < 60 * 60 * 24 * 2)
        $text = '昨天 ' . date('H:i', $time); //两天内
    elseif ($t < 60 * 60 * 24 * 3)
        $text = '前天 ' . date('H:i', $time); // 三天内
    elseif ($t < 60 * 60 * 24 * 30)
        $text = date('m月d日 H:i', $time); //一个月内
    elseif ($t < 60 * 60 * 24 * 365)
        $text = date('m月d日', $time); //一年内
    else
        $text = date('Y年m月d日', $time); //一年以前
    return $text;
}

/**
 * 获取客户端浏览器类型
 * @param  string $glue 浏览器类型和版本号之间的连接符
 * @return string|array 传递连接符则连接浏览器类型和版本号返回字符串否则直接返回数组 false为未知浏览器类型
 */
function get_client_browser($glue = null) {
    $browser = array();
    $agent = $_SERVER['HTTP_USER_AGENT']; //获取客户端信息

    /* 定义浏览器特性正则表达式 */
    $regex = array(
        'ie'      => '/(MSIE) (\d+\.\d)/',
        'chrome'  => '/(Chrome)\/(\d+\.\d+)/',
        'firefox' => '/(Firefox)\/(\d+\.\d+)/',
        'opera'   => '/(Opera)\/(\d+\.\d+)/',
        'safari'  => '/Version\/(\d+\.\d+\.\d) (Safari)/',
    );
    foreach($regex as $type => $reg) {
        preg_match($reg, $agent, $data);
        if(!empty($data) && is_array($data)){
            $browser = $type === 'safari' ? array($data[2], $data[1]) : array($data[1], $data[2]);
            break;
        }
    }
    return empty($browser) ? false : (is_null($glue) ? $browser : implode($glue, $browser));
}

// 获取来自搜索引擎入站时的关键词 @TBD 代码需要优化
if (! function_exists('get_search_engine_keyword')) {
    function get_search_engine_keyword($domain, $path){
        if (empty($domain)) {
            return $arr = array(
                'search_engine'=>'直接访问',
                'keywords'=>'',
            );
        }
        if(strpos($domain, 'google.com.tw')!==false && preg_match('/q=([^&]*)/i',$path,$regs)){
            $searchengine = 'GOOGLE TAIWAN';
            $keywords = urldecode($regs[1]); // google taiwan
        }
        if(strpos($domain,'google.cn')!==false && preg_match('/q=([^&]*)/i',$path,$regs)){
            $searchengine = 'GOOGLE CHINA';
            $keywords = urldecode($regs[1]); // google china
        }
        if(strpos($domain,'google.com')!==false && preg_match('/q=([^&]*)/i',$path,$regs)){
            $searchengine = 'GOOGLE';
            $keywords = urldecode($regs[1]); // google
        }elseif(strpos($domain,'baidu.')!==false && preg_match('/wd=([^&]*)/i',$path,$regs)){
            $searchengine = 'baidu';
            $keywords = urldecode($regs[1]); // baidu
        }elseif(strpos($domain,'baidu.')!==false && preg_match('/word=([^&]*)/i',$path,$regs)){
            $searchengine = 'baidu';
            $keywords = urldecode($regs[1]); // baidu
        }elseif(strpos($domain,'114.vnet.cn')!== false && preg_match('/kw=([^&]*)/i',$path,$regs)){
            $searchengine = 'CT114';
            $keywords = urldecode($regs[1]); // ct114
        }elseif(strpos($domain,'iask.com')!==false && preg_match('/k=([^&]*)/i',$path,$regs)){
            $searchengine = 'IASK';
            $keywords = urldecode($regs[1]); // iask
        }elseif(strpos($domain,'soso.com')!==false && preg_match('/w=([^&]*)/i',$path,$regs)){
            $searchengine = 'SOSO';
            $keywords = urldecode($regs[1]); // soso
        }elseif(strpos($domain, 'sogou.com')!==false && preg_match('/query=([^&]*)/i',$path,$regs)){
            $searchengine = 'sogou';
            $keywords = urldecode($regs[1]); // sogou
        }elseif(strpos($domain,'so.163.com')!==false && preg_match('/q=([^&]*)/i',$path,$regs)){
            $searchengine = 'NETEASE';
            $keywords = urldecode($regs[1]); // netease
        }elseif(strpos($domain,'yodao.com')!== false && preg_match('/q=([^&]*)/i',$path,$regs)){
            $searchengine = 'yodao';
            $keywords = urldecode($regs[1]); // yodao
        }elseif(strpos($domain,'zhongsou.com')!==false && preg_match('/word=([^&]*)/i',$path,$regs)){
            $searchengine = 'ZHONGSOU';
            $keywords = urldecode($regs[1]); // zhongsou
        }elseif(strpos($domain,'search.tom.com')!==false && preg_match('/w=([^&]*)/i',$path,$regs)){
            $searchengine = 'TOM';
            $keywords = urldecode($regs[1]); // tom
        }elseif(strpos($domain,'live.com')!==false && preg_match('/q=([^&]*)/i',$path,$regs)){
            $searchengine = 'MSLIVE';
            $keywords = urldecode($regs[1]); // MSLIVE
        }elseif(strpos($domain, 'tw.search.yahoo.com')!==false && preg_match('/p=([^&]*)/i',$path,$regs)){
            $searchengine = 'YAHOO TAIWAN';
            $keywords = urldecode($regs[1]); // yahoo taiwan
        }elseif(strpos($domain,'cn.yahoo.')!==false && preg_match('/p=([^&]*)/i',$path,$regs)){
            $searchengine = 'YAHOO CHINA';
            $keywords = urldecode($regs[1]); // yahoo china
        }elseif(strpos($domain,'yahoo.')!==false && preg_match('/p=([^&]*)/i',$path,$regs)){
            $searchengine = 'YAHOO';
            $keywords = urldecode($regs[1]); // yahoo
        }elseif(strpos($domain,'msn.com.tw')!==false && preg_match('/q=([^&]*)/i',$path,$regs)){
            $searchengine = 'MSN TAIWAN';
            $keywords = urldecode($regs[1]); // msn taiwan
        }elseif(strpos($domain,'msn.com.cn')!==false && preg_match('/q=([^&]*)/i',$path,$regs)){
            $searchengine = 'MSN CHINA';
            $keywords = urldecode($regs[1]); // msn china
        }elseif(strpos($domain,'msn.com')!==false && preg_match('/q=([^&]*)/i',$path,$regs)){
            $searchengine = 'MSN';
            $keywords = urldecode($regs[1]); // msn
        }elseif(strpos($domain,'haosou.com')!==false && preg_match('/q=([^&]*)/i',$path,$regs)){
            $searchengine = 'haosou';
            $keywords = urldecode($regs[1]);
        }elseif(strpos($domain,'bing.com')!==false && preg_match('/q=([^&]*)/i',$path,$regs)){
            $searchengine = 'bing';
            $keywords = urldecode($regs[1]);
        }elseif(strpos($domain,'chinaso.com')!==false && preg_match('/q=([^&]*)/i',$path,$regs)){
            $searchengine = 'chinaso';
            $keywords = urldecode($regs[1]);
        }else{
            $searchengine = '来源连接访问';
            $keywords = '';
        }
        $arr = array(
            'search_engine'=>$searchengine,
            'keywords'=>$keywords,
        );
        return $arr;
    }

}








